//
//  ConsultationViewController.m
//  Cabinet
//
//  Created by Florent Montsegur on 03/07/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ConsultationViewController.h"
#import "CabinetDefines.h"


@implementation ConsultationViewController

@synthesize mConsultations;

@synthesize mConsDay;
@synthesize mConsNum;
@synthesize mConsDate;
@synthesize mConsNom;
@synthesize mConsPrenom;
@synthesize mConsDiag;
@synthesize mConsRef;
@synthesize mConsTraitement;
@synthesize mConsMoyenPaiement;
@synthesize mConsActe;
@synthesize mConsPaye;
@synthesize mConsSomme;
@synthesize mRenouvellement;
@synthesize mEnregistrer;

@synthesize mAge;
@synthesize mTraitantMe;
@synthesize mNaissance;

@synthesize mFeuilleDone;
@synthesize mFeuilleGiven;
@synthesize mFeuilleNone;

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}


- (NSString*)windowNibName
{
	return @"ViewConsult";
}

- (void)windowDidLoad
{
    [super windowDidLoad];
    
    [[[self mConsSomme] formatter] setFormat:@".00"];
    
    [self showConsultation:mConsultation];
}

- (void) closeWindow
{
    [[self window] orderOut:nil];
    [NSApp stopModal];
}

- (IBAction)okAction:sender {
    
    NSLog(@"On OK");
    
    [self fillConsultation:mConsultation];
    
    mResult = NSOKButton;
    [self closeWindow];
    
    if(mIEnregistrerNotifiable != nil)
        [mIEnregistrerNotifiable Enregistre];
}

- (IBAction)annulerAction:sender {
    
    NSLog(@"On Annuler");
    
    mResult = NSCancelButton;
    [self closeWindow];
}

- (void) setIEnregistrerNotifiable: aIEnregistrerNotifiable{
    
    mIEnregistrerNotifiable = (id<IEnregistrerNotifiable>)aIEnregistrerNotifiable;
}


- (int) returnCode
{
    return mResult;
}


- (void)setConsultation:(Consultation*)aConsultation
{
    mConsultation = aConsultation;
}

-(void) showConsultation:(Consultation *)aConsultation
{
    if(aConsultation == nil)
        return;
        
    [[self mConsDate] setDateValue:[aConsultation CreationDate]];
    [[self mConsDiag] setStringValue:[aConsultation Diagnostic]];
    [[self mConsRef] setStringValue:[aConsultation Reference]];
    [[self mConsTraitement] setString:[aConsultation Traitement]];
    [[self mConsMoyenPaiement] setStringValue:[aConsultation Payement]];
    [[self mConsActe] setStringValue:[aConsultation Acte]];
    [[self mConsSomme] setStringValue:[[aConsultation Somme] stringValue]];
    
    [[self mFeuilleNone] setIntValue:([[aConsultation EtatFeuille] intValue] == FeuilleNonFaite ? 1 : 0)];
    [[self mFeuilleDone] setIntValue:([[aConsultation EtatFeuille] intValue] == FeuilleGardee ? 1 : 0)];
    [[self mFeuilleGiven] setIntValue:([[aConsultation EtatFeuille] intValue] == FeuilleDonnee ? 1 : 0)];
        
    [[self mConsPaye] setIntValue:[[aConsultation Paye] intValue]];
        
    [self showPerson:[aConsultation Person]];

}

- (void) showPerson:(Person*)aPerson
{
    if(aPerson == nil)
        return;
    
    [[self mConsNom] setStringValue:[aPerson Nom] ];
    [[self mConsPrenom] setStringValue:[aPerson Prenom] ];
    [[self mNaissance] setDateValue:[aPerson Naissance] ];
    
    [[self mTraitantMe] setState: [[aPerson MedecinTraitant] intValue]];
    
    // TODO: afficher age
    NSDate *minval = [NSCalendarDate dateWithString:@"1870-01-01 00:00:00 +0000"];
    if( ![[aPerson Naissance] isEqualToDate:minval] )
    {
        NSInteger age = [self calculAge:[aPerson Naissance]];
        [[self mAge] setStringValue:[NSString stringWithFormat:@"%ld an%@", age, (age>1?@"s":@"")]];
    }
    else
        [[self mAge] setStringValue:@""];
    
    //[mConsulationCtrl setConsultations:[[aPerson Consultations] allObjects]];
    // [[self mConsultations] reloadData];
    
}

- (NSInteger)calculAge:(NSDate *)aNaissance 
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents *dateComponentsNow = [calendar components:unitFlags fromDate:[[self mConsDate] dateValue ]];
    NSDateComponents *dateComponentsBirth = [calendar components:unitFlags fromDate:aNaissance];
    
    if (([dateComponentsNow month] < [dateComponentsBirth month]) ||
        (([dateComponentsNow month] == [dateComponentsBirth month]) && ([dateComponentsNow day] < [dateComponentsBirth day]))) {
        return [dateComponentsNow year] - [dateComponentsBirth year] - 1;
    }
    
    return [dateComponentsNow year] - [dateComponentsBirth year];
}

- (NSString*) formatInput:(NSTextField*)aTextField {
    if( aTextField == nil )
        return @"";
    
    if( [aTextField stringValue] == nil )
        return @"";
    
    return [NSString stringWithFormat:@"%@", [aTextField stringValue]];
}

- (NSString*) formatTVInput:(NSTextView*)aTextView {
    if( aTextView == nil )
        return @"";
    
    if( [aTextView string] == nil )
        return @"";
    
    return [NSString stringWithFormat:@"%@", [aTextView string]];
}

- (NSInteger)getFeuille
{
    if([mFeuilleDone intValue] == 1 )
        return FeuilleGardee;
    
    if([mFeuilleGiven intValue] == 1 )
        return FeuilleDonnee;
    
    return FeuilleNonFaite;
}


- (void) fillConsultation:(Consultation*)aConsultation{
    
           
    [[aConsultation Person] setMedecinTraitant:[NSNumber numberWithInteger:[[self mTraitantMe] state]]];
    [[aConsultation Person] setNaissance:[[self mNaissance] dateValue]];
    
    [aConsultation setCreationDate:[[self mConsDate] dateValue]];
    [aConsultation setDiagnostic:[self formatInput:mConsDiag] ];
    [aConsultation setReference:[self formatInput:mConsRef] ];
    [aConsultation setPayement:[self formatInput:mConsMoyenPaiement] ];
    [aConsultation setActe:[self formatInput:mConsActe] ];
    [aConsultation setEtatFeuille:[NSNumber numberWithInteger:[self getFeuille]]];
    [aConsultation setPaye:[NSNumber numberWithInteger:[[self mConsPaye] state]]];
    
    [aConsultation setTraitement:[self formatTVInput:mConsTraitement] ];
    
    NSString *somme = [self formatInput:mConsSomme];
    if( [somme length] <= 0 )
        somme = [somme stringByAppendingFormat:@"0"];
    
    NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:somme locale:[[NSUserDefaults standardUserDefaults]dictionaryRepresentation]];
    [aConsultation setSomme:decimal ];
}


- (IBAction)chequeAction:sender
{
    [mConsMoyenPaiement setStringValue:@"Cheque"];
    [[self mConsPaye] setState:1];
}

- (IBAction)especesAction:sender
{
    [mConsMoyenPaiement setStringValue:@"Especes"];
    [[self mConsPaye] setState:1];
}

- (IBAction)aldAction:sender
{
    [mConsMoyenPaiement setStringValue:@"ALD"];
    [[self mConsPaye] setState:0];
}

- (IBAction)cmuAction:sender
{
    [mConsMoyenPaiement setStringValue:@"CMU"];
    [[self mConsPaye] setState:0];
}

- (IBAction)atAction:sender
{
    [mConsMoyenPaiement setStringValue:@"AT"];
    [[self mConsPaye] setState:0];
}

- (IBAction)artAction:sender
{
    [mConsMoyenPaiement setStringValue:@"Art 115"];
    [[self mConsPaye] setState:0];
}

- (BOOL)textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
    
    if (commandSelector == @selector(insertTab:)) {
        [[textView window] selectNextKeyView:[textView nextResponder]];
        return YES;
    }
    else if (commandSelector == @selector(insertBacktab:)) {
        [[textView window] selectPreviousKeyView:[textView nextResponder]];
        return YES;
    }
    
    return NO;
}

@end
